'''
@author: haiwen
@date: 2020/9/23
@file: common.py
'''


import requests
from conf.env import user,host
from pylib.pulgins import Config
class User():
    def __init__(self,email=None,psw=None):
        #如果不指定具体的邮箱和密码，就从配置文件读取
        if email:
            self.email=email
        else:
            self.email=user['email']
        if psw:
            self.psw=psw
        else:
            self.psw=user['psw']

    #实现登录
    def login(self):
        payload={"user":{"email":self.email},"password":self.psw,"code":"","locale":"zhcn"}
        resp=requests.post(f'{host}/accounts/password/authenticate',json=payload)
        return resp.cookies    #认证信息

    def logout(self):
        pass

    def register(self):
        pass

#api基类-被具体的业务API类继承
class BaseAPI():
    def __init__(self,cookies=None):
        self.host=host
        #获取当前类的名称
        current_class=self.__class__.__name__
        #根据当前class名称获取API相关配置
        self.conf=Config.read_yml('conf/api_conf.yml')[current_class]
        self.url=self.conf['url']#配置文件获取Url
        #如果传递了cookies
        if cookies:
            #正式测试的时候，需要统一cookies
            self.cookies=cookies
        else:
            #用于临时测试产生cookies或者本轮测试只针对一个接口
            self.cookies=User().login()

        #从cookies获取spaceid
        self.spaceid=dict(self.cookies)['X-Space-Id']

    def add(self,**kw):
        payload=self.conf['add']
        payload.update(kw) #更新用户的传参
        payload['space']=self.spaceid #使用实际的spaceid
        resp=requests.post(f'{host}{self.url}',json=payload,cookies=self.cookies)
        return resp.json()['value'][0]

    def edit(self,_id,**kw):
        payload = self.conf['edit']
        payload.update(kw)  # 更新用户的传参
        payload['space'] = self.spaceid  # 使用实际的spaceid
        #把字段嵌套到$set中
        data={}
        data['$set']=payload
        resp = requests.put(f'{host}{self.url}/{_id}', json=data, cookies=self.cookies)
        return resp.json()

    def delete(self,_id):
        resp=requests.delete(f'{host}{self.url}/{_id}',cookies=self.cookies)
        return resp.json()

    def list_all(self):
        resp=requests.get(f'{host}{self.url}',cookies=self.cookies)
        return resp.json()['value']

    #删除所有
    def del_all(self):
        objs=self.list_all()
        for obj in objs:
            self.delete(obj['_id'])

